package com.pan.kang.framework;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.Serializable;

public abstract class GeneralRestService<Model extends IDataModel, ID extends Serializable,
        CT extends IContext<Model, ID>> implements IRestService {

    @Autowired
    private CT context;
    public GeneralRestService() {
    }

    protected CT getContext() {
        return this.context;
    }

    public void setContext(CT newContext) {
        this.context = newContext;
    }

    @RequestMapping(value = "/add", method = {RequestMethod.POST})
    @ResponseBody
    public ID add(@RequestBody Model model) {
        if (model == null) {
            return null;
        }
        this.getContext().save(model);
        if (model instanceof IIdentifyModel) {
            return (ID) ((IIdentifyModel<?>) model).getGid();
        }
        throw new RuntimeException("实体类需实现 IIdentifyModel 接口");
    }

    @RequestMapping(value = "/update", method = {RequestMethod.POST})
    @ResponseBody
    public Model update(@RequestBody Model model) {
        this.getContext().save(model);
        return model;
    }

    @RequestMapping(value = "/deleteId", method = {RequestMethod.POST})
    @ResponseBody
    public ID deleteGid(@RequestParam(value = "gid",required = true) ID gid) {
        this.getContext().deleteByKey(gid);
        return gid;
    }
}
